package cn.nawang.ebeim.api.comm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.nawang.ebeim.api.domain.User;
import cn.nawang.ebeim.api.service.RedisService;
import cn.nawang.ebeim.api.service.UserService;
import cn.nawang.ebeim.api.utils.Constant;
import cn.nawang.ebeim.api.utils.HttpTokenUtils;
import cn.nawang.ebeim.api.utils.JsonUtil;
import cn.nawang.ebeim.api.utils.ValidateUtil;

/**
 * @ClassName: ApiInterceptor
 * @Description: TODO
 * @author fanyb
 * @date Sep 24, 2015 10:13:39 AM
 * @version v1.0
 */
public class ApiInterceptor implements HandlerInterceptor {

  
  @Autowired
  private RedisService redisService;
  
  @Autowired
  private UserService userService;

  public String[] allowUrls;// 还没发现可以直接配置不拦截的资源，所以在代码里面来排除

  public void setAllowUrls(String[] allowUrls) {
    this.allowUrls = allowUrls;
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
    if (null != allowUrls && allowUrls.length >= 1) for (String url : allowUrls) {
      if (requestUrl.contains(url)) {
        return true;
      }
    }
    String token = request.getParameter("token");
    if (ValidateUtil.isEmpty(token)) {
      // 如果不存在令牌
      // 返回未登录的指令
      request.getRequestDispatcher("/login/fail").forward(request, response);
      return false;
    }
    // 解析令牌
    JSONObject tokenJson = HttpTokenUtils.parseHttpToken(token);
    // 判断秘钥是否被修改
    if (!HttpTokenUtils.checksum(tokenJson)) {
      // 失败
      response.addHeader("message",Constant.HTTP_TOKEN_VERIFY_ZERO);
      request.getRequestDispatcher("/login/token_expired").forward(request, response);
      return false;
    }
    boolean isExist = redisService.exists(token);
    if (!isExist) {
      response.addHeader("message",Constant.HTTP_TOKEN_VERIFY_ONE);
      request.getRequestDispatcher("/login/token_expired").forward(request, response);
      return false;
    }
    String userID = JsonUtil.getJsonString(tokenJson, "userID");
    User user=userService.findOne(userID);
    if(user==null){
      //用户不存在
      response.addHeader("message",Constant.HTTP_TOKEN_VERIFY_TWO);
      request.getRequestDispatcher("/login/token_expired").forward(request, response);
      return false;
    }
    if(user.getStatus().equals(Constant.USER_STATUS_TYPE_ONE)){
      //用户被禁用了
      response.addHeader("message",Constant.HTTP_TOKEN_VERIFY_THREE);
      request.getRequestDispatcher("/login/token_expired").forward(request, response);
      return false;
    }
    
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
    // TODO Auto-generated method stub

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {
    // TODO Auto-generated method stub

  }

}
